<template>
    <view class="easy-num">
        <view class="easy-num-box">
            <button class="btn btn-minus" :class="ite.Amount <= 0 ? 'disable' : ''"
                @click="changeAmount($event, ite, item, -1)">
                <text>-</text>
            </button>
            <view class="btn-input-box" @click="focusFn(ite, item, 0)">
                <view class="input-mark" :class="ite.Amount.toString().length > 6 ? 'text-show-line-1' : ''">{{
                    ite.Amount }}</view>
                <!-- #ifdef MP -->
                <!-- <input :selection-start="start" :selection-end="end" confirm-type="done" :focus="isFocus" type="text" @input="inputChangeFn" v-model="amount" :style="{width:inputW}"  class="btn-input btn-input123"
					@blur="changeAmount($event,ite,item,0)"> -->
                <!-- #endif -->
                <!-- #ifndef MP -->
                <!-- 	<input type="text" v-model="amount" class="btn-input" confirm-type="done" :style="{width:inputW}"  @input="inputChangeFn" @blur="changeAmountCus(ite,item,0)">
					<view class="num-box-mark">
						<text class="num-text-mark" :class="{'selectAll':isFirstFocus}">{{amount}}</text>
					</view> -->
                <!-- #endif -->
            </view>
            <button class="btn btn-plus" :disabled="ite.Amount >= ite.Stock && !displayData.NoCheckStock" :class="{
                disable: ite.Amount >= ite.Stock && !displayData.NoCheckStock,
                disable: item.CurrentStock <= 0 && !displayData.NoCheckStock,
            }" @click="changeAmount($event, ite, item, 1)">
                <!-- @click="changeAmount(ite,item,1)" -->
                <text>+</text>
            </button>
        </view>
        <num-popup v-if="numPopShow" :amount="amount"></num-popup>
    </view>
</template>

<script>
import { updateCart, getUserTempCarList } from "@/utils/cartUtil.js"
import { getUserCarList } from "@/service/api/member.js"
import utilsOld from "@/utils/utilsOld.js"
import numPopup from "@/components/order/num-popup.vue"
import storage from "@/uni-sub-base/utils/storage.js"
export default {
    comments: {},
    components: {
        numPopup,
    },
    props: {
        ite: {
            type: Object,
            default: () => { },
        },
        item: {
            type: Object,
            default: () => { },
        },
        refresh: {
            type: Boolean,
            default: false,
        },
        displayData: {
            type: Object,
            required: true,
        },
        orderType: {
            type: Number,
            default: 0,
        },
        isTempCar: {
            type: Boolean,
            default: false,
        }
        // inputAmount: {
        // 	type:String,
        // 	default: ''
        // },
    },
    watch: {
        refresh(e) {
            if (e) {
                this.amount = this.ite.Amount
                this.changeW(this.amount.toString())
                this.$forceUpdate()
            }
        },
    },
    data() {
        return {
            numPopShow: false,
            start: -1,
            end: -1,
            isFocus: false,
            type: "number",
            amount: 0,
            isFirstFocus: false,
            refreshs: false,
            inputW: "50rpx",
        }
    },
    mounted() {
        this.amount = this.ite.Amount
        this.changeW(this.amount.toString())
    },
    methods: {
        async checkProIsInCart(item) {
            let result = null
            let datas = await getUserTempCarList({ isTempCar: true })
            datas.forEach((e) => {
                if (e.ProductId == item.ProductId) {
                    e.SubItems.forEach((sub) => {
                        if (sub.UnitId == item.UnitId && sub.SkuId == item.SkuId) {
                            result = sub
                        }
                    })
                }
            })
            return result
        },
        changeAmount(e, ite, item, type) {
            console.log(item)
            let token = storage.getCache("token")
            if (!token || token == "") {
                this.$showModal({ show: true })
                return
            }
            this.reSet()
            // this.amount = this.amount.replace(/\b(0+)/gi,"")
            if (type == 1) {
                // this.$refs.carAnmation.touchOnGoods(e,item);
            }
            ite.Amount = this.amount
            this.changeAmountFn(ite, item, type)
            // this.$emit('changeAmountFn',ite,item,type)
        },
        changeAmountCus(ite, item, type) {
            this.isFirstFocus = false
            if (this.amount) {
                this.amount = this.amount.toString().replace(/\b(0+)/gi, "")
                ite.Amount = Number(this.amount)
            }
            this.$emit("changeAmountFn", ite, item, type)
        },
        async changeAmountFn(item, ite, type) {
            console.log("changeAmountFn", item, ite, type)
            let num = Number(item.Amount)
            let stock = ite.V_StockSum
            console.log("stock", stock)
            let UnitRatio = item.Ratio
            let minNum = 0
            let addNum = 1
            let LimitBuy = 0
            if (ite.ProductSkuList[0].MinimumOrder > 0) {
                minNum = ite.ProductSkuList[0].MinimumOrder
            } else {
                minNum = ite.MinNum
            }
            if (ite.ProductSkuList[0].AddNum > 0) {
                addNum = ite.ProductSkuList[0].AddNum
            } else {
                addNum = item.Ratio && UnitRatio == 1 ? ite.AddNum : 1
            }
            if (ite.ProductSkuList[0].LimitBuy > 0) {
                LimitBuy = ite.ProductSkuList[0].LimitBuy
            } else {
                LimitBuy = ite.LimitBuy
            }
            const _oldAmount = item.Amount
            if (this.displayData.NoCheckStock) {
                if (type != 0) {
                    item.Amount = num + Number(type) * addNum
                    if (type == -1 && item.Amount * UnitRatio < minNum) {
                        item.Amount = 0
                    } else if (item.Amount * UnitRatio < minNum) {
                        minNum = parseInt(minNum / UnitRatio) + (minNum % UnitRatio > 0 ? 1 : 0)
                        let addN = minNum % addNum
                        let newNum = minNum
                        item.Amount = newNum
                    }
                } else {
                    if (num > 0) {
                        let addN = num % addNum
                        let newNum = num
                        item.Amount = newNum
                        if (item.Amount * UnitRatio < minNum) {
                            minNum = parseInt(minNum / UnitRatio) + (minNum % UnitRatio > 0 ? 1 : 0)
                            let addN = minNum % addNum
                            let newNum = num
                            item.Amount = newNum
                        }
                    } else {
                        item.Amount = 0
                    }
                }
                if (item.Amount < 0) {
                    item.Amount = 0
                }
            } else {
                utilsOld.changeAmountNew(item, num, stock, type, minNum, UnitRatio, LimitBuy, addNum)
            }
            this.Amount = item.Amount
            this.$forceUpdate()
            //商品
            if (_oldAmount !== item.Amount || type === 0) {
                console.log("isTempCar", this.isTempCar)
                if (this.isTempCar) {
                    //先判断是购物车里是已经有该商品
                    // let result = await this.checkProIsInCart(item);
                    // console.log("result", result)
                    let carResult = await getUserCarList({ isTempCar: true });
                    let param = [];
                    let carData = carResult.Data || [];
                    if (carData.length > 0) {
                        carData.forEach((item) => {
                            param.push({
                                ProductId: item.ProductId,
                                Amount: item.Amount,
                                SkuId: item.SkuId,
                                UnitId: item.UnitId,
                                UnitName: item.UnitName,
                                Ratio: item.Ratio,
                            })
                        })
                    }
                    let filterArr = param.filter(e => e.ProductId == item.ProductId && e.SkuId == item.SkuId && e.UnitId == item.UnitId)
                    console.log("filterArr", filterArr)
                    if (filterArr.length > 0) {
                        let index = param.findIndex(e => e.ProductId == item.ProductId && e.SkuId == item.SkuId && e.UnitId == item.UnitId)
                        console.log("index", index)
                        param[index].Amount = item.Amount
                    } else {
                        console.log("新增加")
                        param.push({
                            ProductId: item.ProductId,
                            Amount: item.Amount,
                            SkuId: item.SkuId,
                            UnitId: item.UnitId,
                            UnitName: item.UnitName,
                            Ratio: item.Ratio,
                        })
                    }
                    console.log("param", param)
                    updateCart(param, false, true, this.orderType, "", this.isTempCar).then((res) => { })
                } else {
                    const _obj = {}
                    _obj.ProductId = item.ProductId
                    _obj.Amount = item.Amount
                    _obj.SkuId = item.SkuId
                    _obj.UnitId = item.UnitId
                    _obj.UnitName = item.UnitName
                    _obj.Ratio = item.Ratio
                    let param = []
                    param.push(_obj)
                    updateCart(param, false, true, this.orderType, "", this.isTempCar).then((res) => { })
                }
            }
            this.$forceUpdate()
        },
        focusFn(ite, item, type) {
            let token = storage.getCache("token")
            if (!token || token == "") {
                this.$showModal({ show: true })
                return
            }
            // this.isFocus = true
            // this.start = 0
            // this.end = this.ite.Amount.toString().length;

            this.$emit("amountProp", ite, item, type, this.displayData)
        },
        reSet() {
            this.isFocus = false
            this.start = -1
            this.end = -1
        },
        inputFn(e) {
            let str = e.detail.value
            str = str.replace(/\b(0+)/gi, "")
            let newStr = str.charAt(str.length - 1)
            // this.amount = this.amount.replace(/\b(0+)/gi,"")
            if (this.isFirstFocus) {
                // let old = newStr
                this.amount = newStr
                // this.refreshs = true
                // this.$nextTick(()=>{
                // 	this.refreshs = false
                // })
                // this.$forceUpdate()
            } else {
                // this.amount = value
            }

            this.isFirstFocus = false
        },
        focusCus() {
            this.isFirstFocus = true
        },
        inputChangeFn(e) {
            let str = e.detail.value
            this.changeW(str)
        },
        changeW(str) {
            if (str.length >= 6) {
                this.inputW = "90rpx"
            } else if (str.length >= 3) {
                this.inputW = 50 + str.length * 6 + "rpx"
            } else {
                this.inputW = "50rpx"
            }
        },
    },
}
</script>

<style lang="scss">
.easy-num-box {
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
    flex: 1;
    border: solid 1rpx #b2b2b2;
    border-radius: 100rpx;
    padding: 4rpx 6rpx;
    height: 52rpx;

    .btn-input-box {
        position: relative;
        padding: 0 4rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        width: auto;
        min-width: 90rpx;

        .btn-input {
            padding: 0 8rpx;
            position: relative;
            z-index: 1;
            height: 52rpx;
            line-height: 1;
            border: none;
            background: transparent;
            text-align: center;
            font-size: $font-size-26;
            outline: none;
            color: (0, 0, 0, 0.1);
        }

        .text-show-line-1 {
            width: 90rpx;
        }
    }

    .btn-minus,
    .btn-plus {
        justify-content: center;
        align-items: center;
        position: relative;
        font-size: 58rpx;
        line-height: 52rpx;
        height: 52rpx;
        width: 52rpx;
        overflow: hidden;
        border-radius: 100rpx;
        background: #e8e8e8;
        display: flex;
        justify-content: center;
        align-items: center;

        &:before {
            content: "";
            position: absolute;
            width: 100%;
            height: 100%;
            top: 0;
            left: 0;
        }

        text {
            font-size: 40rpx;
            position: relative;
            top: -4rpx;
        }
    }

    .btn-plus {
        background: $app-color-main;

        text {
            color: #ffffff;
        }
    }

    .color-shadow {
        // opacity: 0.1
    }

    .disable {
        // opacity: 0.3;
        // text{
        // 	color:#e9e9e9;
        // }
    }
}

.btn-input-box {
    height: 44rpx;
    // width: 90rpx;
    padding: 0 5rpx;

    &:before {
        background: $transparent;
    }

    .btn-input {
        font-size: $font-size-26;
    }
}

.input-number-box {
    border-radius: 100rpx;
    padding: 4rpx 6rpx;
    border: solid 1rpx #b2b2b2;
    background: #ffffff;

    .btn {
        width: 42rpx;
        height: 42rpx;
        border-radius: 100rpx;
        background: #f2f2f2;
        border: none;
        padding: 0;

        text {
            color: $color-black;
        }
    }

    .disable {
        border: none;

        text {
            color: #cccccc;
        }
    }
}

.selectAll {
    padding: 0 8rpx;
    background: rgba(0, 0, 0, 0.2);
}

.num-box-mark {
    position: absolute;
    left: 0;
    right: 0;
    height: 26rpx;
    display: flex;
    justify-content: center;
    align-items: center;

    text {
        color: $transparent;
    }
}

.input-mark {
    // content: "";
    // position: absolute;
    // width: 100%;
    // height: 100%;
    // max-height: 52rpx;
    // top: 0;
    // left: 0;
    // z-index: 2;
    // display: flex;
    // justify-content: center;
    // align-items: center;
    display: block;
    text-align: center;
    font-size: $font-size-26;
}
</style>
